package com.ruoyi.system.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.DetectionCycle;
import com.ruoyi.system.domain.Person;
import com.ruoyi.system.domain.Ptesting;
import com.ruoyi.system.domain.vo.DetectionCycleTimeVo;
import com.ruoyi.system.domain.vo.PersonTimeVo;
import com.ruoyi.system.mapper.DetectionCycleMapper;
import com.ruoyi.system.mapper.PersonMapper;
import com.ruoyi.system.mapper.PtestingMapper;
import com.ruoyi.system.mapper.RcpCollectResultDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component("busTask")
public class BusTaskInfos {

    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private PtestingMapper ptestingMapper;
    @Autowired
    private DetectionCycleMapper detectionCycleMapper;
    @Autowired
    private RcpCollectResultDataMapper rcpCollectResultDataMapper;

    /**
     * 定时每天12点启动自动跟新数据库数据
     */
    public void creatTaskOrderInfos() throws Exception {
        //查询重点人群所有数据
        List<Person> Personlist = personMapper.selectPersonListAll(new Person(0, 0)); //删除标志（0代表存在 2代表删除）审核通过/未审核  0通过1未审核
        try {

            for (Person person : Personlist) {
                String startTime = (DateUtils.dateTime(DateUtils.dateAddOne(new Date(), -1))) + " 00:00:00"; //开始时间
                String endTime = (DateUtils.dateTime(new Date())) + " 23:59:59";//yyyy-MM-dd   结束时间
                List<Map> selectRcps = rcpCollectResultDataMapper.selectRcp(person.getCardId(), startTime, endTime);
                if (selectRcps.size() > 0) {
                    //删除本地近48小时的核酸
                    ptestingMapper.deletePtestingByPtesting(new Ptesting(startTime, endTime, person.getPersonId()));
                    for (Map map : selectRcps) {
                        //检测时间或者检测结果为空的情况下不进行新增
                        if (StringUtils.isNull(map.get("cy_time")) || StringUtils.isNull(map.get("state"))) {
                            continue;
                        }
                        Ptesting ptesting = new Ptesting();
                        ptesting.setDetectionTimeStr(map.get("cy_time") + "");//核酸日期
                        ptesting.setCardId(person.getCardId());  //身份证号
                        ptesting.setDeptId(person.getDeptId()); //行业id
                        ptesting.setPersonId(person.getPersonId());//重点人群id
                        ptesting.setDetectionCycleId(person.getDetectionCycleId());
                        ptesting.setDetectionResult((map.get("state") + "").contains("阴") ? 1L : 2L); //阴性是1,阳性是2
                        ptesting.setPersonName(person.getPersonName());//姓名
                        ptesting.setPhoneNumber(person.getPhoneNumber());//手机号
                        ptesting.setCreateTime(new Date()); //创建时间
                        ptestingMapper.insertPtesting(ptesting);
                    }
                }
            }
            //清空数据表
            rcpCollectResultDataMapper.delectDetectionCycleTime();
            //循环所有的期数
            List<DetectionCycle> detectionCycles = detectionCycleMapper.selectDetectionCycleList(new DetectionCycle());
            for (DetectionCycle detectionCycle : detectionCycles) {
                String startTime = detectionCycle.getStartTime();//期数开始时间
                if (detectionCycle.getTianyue() == 1) {  //天的情况
                    List<Map<Object, String>> dates = findDates(startTime, DateUtils.dateTime(new Date()), detectionCycle.getDays());
                    for (Map map : dates) {
                        rcpCollectResultDataMapper.insetDetectionCycleTime(new DetectionCycleTimeVo(map.get("starTime") + "", map.get("entTime") + "", detectionCycle.getId(), detectionCycle.getFrequency()));
                    }
                } else { //月的情况
                    List<Map<Object, String>> month = findMonth(startTime, DateUtils.dateTime(new Date()), detectionCycle.getDays());
                    for (Map map : month) {
                        rcpCollectResultDataMapper.insetDetectionCycleTime(new DetectionCycleTimeVo(map.get("starTime") + "", map.get("entTime") + "", detectionCycle.getId(), detectionCycle.getFrequency()));
                    }
                }
            }
            //清空person_time数据表
            rcpCollectResultDataMapper.delectPersonTime();
            //循环所有期数统计核酸数量
            List<DetectionCycleTimeVo> detectionCycleTimeVos = rcpCollectResultDataMapper.selectDetectionCycleTime();
            for (DetectionCycleTimeVo detectionCycleTimeVo : detectionCycleTimeVos) {
                //循环类别拿到该类别的人员
                List<Person> Personlists = personMapper.selectPersonListAll(new Person(0, 0, detectionCycleTimeVo.getDetectionCycleId())); //删除标志（0代表存在 2代表删除）审核通过/未审核  0通过1未审核
                for (Person Person : Personlists) {
                    //拿到这个人某个时间段的核酸信息
                    List<Ptesting> ptestings = ptestingMapper.selectPtestingList(new Ptesting(detectionCycleTimeVo.getStarTime(), detectionCycleTimeVo.getEndTime(), Person.getPersonId()));
                    //核算信息记录表
                    PersonTimeVo personTimeVo = new PersonTimeVo();
                    personTimeVo.setPersonName(Person.getPersonName()); //姓名
                    personTimeVo.setSex(Person.getSex());//性别
                    personTimeVo.setPersonAge(Person.getPersonAge());//年龄
                    personTimeVo.setWorkAddress(Person.getWorkAddress());//工作地点
                    personTimeVo.setCardId(Person.getCardId());//身份证号
                    personTimeVo.setPhoneNumber(Person.getPhoneNumber());//手机号
                    personTimeVo.setAddress(Person.getAddress());//家庭住址
                    personTimeVo.setEnterpriseName(Person.getEnterpriseName());//企业名称
                    personTimeVo.setDetectionCycleId(Person.getDetectionCycleId());//类别id
                    personTimeVo.setDeptId(Person.getDeptId());//部门id
                    personTimeVo.setDetectionCycleTimeId(detectionCycleTimeVo.getId()); //期数id
                    personTimeVo.setFrequency(detectionCycleTimeVo.getFrequency());//当期应检次数（应检频率）
                    personTimeVo.setFrequencyAlready(ptestings.size());//档期已检次数（已检频率）
                    rcpCollectResultDataMapper.insetPersonTimeVo(personTimeVo);
                    //判断当前时间是第几期
                    long StarTime = DateUtils.parseDate(detectionCycleTimeVo.getStarTime()).getTime();
                    long EndTim = DateUtils.parseDate(detectionCycleTimeVo.getEndTime()).getTime();
                    long time = new Date().getTime();
                    //判断是否是当期，并且跟新person表是否完场检测
                    if (StarTime <= time && time <= EndTim) {
                        Person.setFrequency(Long.valueOf(ptestings.size() + "")); //当前期数已检次数
                        if (ptestings.size() >= detectionCycleTimeVo.getFrequency()) {
                            Person.setFalg(0L); //0已完成1未完成
                        } else {
                            Person.setFalg(1L); //0已完成1未完成
                        }
                        personMapper.updatePerson(Person);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * 天的情况统计所有的期数
     *
     * @param stime     开始时间
     * @param etime     结束时间
     * @param frequency 几天
     * @return
     * @throws ParseException
     */
    public static List<Map<Object, String>> findDates(String stime, String etime, Long frequency) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        stime = DateUtils.dateTime(sdf.parse(stime));
        etime = DateUtils.dateTime(sdf.parse(etime));
        List<String> dates = DateUtils.findDates(stime, etime);
        List<Map<Object, String>> list = new ArrayList();
        if (dates.size() > 0) {
            //能整除就不加，不能整除就加一
            int c = (int) ((int) dates.size() / frequency + (dates.size() % frequency != 0 ? 1 : 0));
            String staime = stime;
            for (int a = 0; a < c; a++) {
                Map map = new HashMap();
                map.put("starTime", staime + " 00:00:00");
                String s = DateUtils.dateTime(DateUtils.dateAddOne(DateUtils.parseDate(staime), Integer.parseInt((frequency - 1) + "")));
                staime = DateUtils.dateTime(DateUtils.dateAddOne(DateUtils.parseDate(staime), Integer.parseInt(frequency + "")));
                map.put("entTime", s + " 23:59:59");
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 月的情况统计所有的期数
     *
     * @param stime     开始时间
     * @param etime     结束时间
     * @param frequency 几天
     * @return
     * @throws ParseException
     */
    public static List<Map<Object, String>> findMonth(String stime, String etime, Long frequency) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        stime = DateUtils.dateTime(sdf.parse(stime));
        etime = DateUtils.dateTime(sdf.parse(etime));
        List<String> monthBetween = DateUtils.getMonthBetween(stime, etime);
        List<Map<Object, String>> list = new ArrayList();
        if (monthBetween.size() > 0) {
            //能整除就不加，不能整除就加一
            int c = (int) ((int) monthBetween.size() / frequency + (monthBetween.size() % frequency != 0 ? 1 : 0));
            String staime = stime;
            for (int a = 0; a < c; a++) {
                Map map = new HashMap();
                map.put("starTime", stime + " 00:00:00");
                String s = DateUtils.dateTime(DateUtils.monthAddOne(DateUtils.parseDate(staime), Integer.parseInt((frequency - 1) + "")));
                staime = DateUtils.dateTime(DateUtils.monthAddOne(DateUtils.parseDate(staime), Integer.parseInt(frequency + "")));
                map.put("entTime", DateUtils.getLastDayOfMonth(Integer.parseInt(s.split("-")[0]), Integer.parseInt(s.split("-")[1])) + " 23:59:59");
                list.add(map);
            }
        }
        return list;
    }
}
